<template>
    <div class="page-controller">
      <FISearchForm
        class="box-radius2"
        ref="ruleFormRef"
        :id="`inqu_${tableId}`"
        v-model:form-value="state.query"
        :table-column="columns"
        :wrapperSpan="searchWrapperSpan"
        @submit="searchFn"
      >
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem prop="tagCode" label="标签编码">
            <FIInput v-model="state.query.tagCode" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem prop="tagName" label="标签名称">
            <FIInput v-model="state.query.tagName" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem prop="groupCode" label="标签分组">
            <tagGroupSelect v-model="state.query.groupCode"/>

          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem prop="tagState" label="状态">
            <FISelect
                v-model="state.query.tagState"
                valueCustom="value"
                :options="dataArr"
                clearable
              />
          </FIFormItem>
        </el-col>
      </FISearchForm>
      <div class="margin-bottom20"></div>
      <FITable
        ref="tableRef"
        class="box-radius2"
        title="记录集"
        :id="`result_${tableId}`"
        :readonly="false"
        :data="state.dataList"
        primaryKey="tagId"
        :rowNo="true"
        v-model:columns="columns"
        :insertable="false"
        :isLoading="isTableLoading"
        :saveSuccessful="saveSuccessful"
        :pageConfig="pageConfig"
        :showSaveModel="false"
        @table-refresh="searchFn"
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentChange"
        @action-click="actionClick"
      >
        <template #headerBtn>
          <FIButton id="insertTag" class="margin-left5" border @click.stop="btnClick"></FIButton>
        </template>
      </FITable>
      <FIModel v-model="editShow" width="500" title="新增/编辑" @close="closeClick">
          <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="editData"
            :rules="registerRules"
            label-width="auto"
            class="demo-ruleForm"
            status-icon
          >
          <el-form-item label="标签编码" prop="tagCode">
            <FIInput v-model="editData.tagCode" clearable :disabled="isEdit"/>
          </el-form-item>
          <el-form-item label="标签名称" prop="tagName">
            <FIInput v-model="editData.tagName" clearable />
          </el-form-item>
          <el-form-item label="标签分组" prop="groupCode">
            <tagGroupSelect v-model="editData.groupCode" style="width:85%"/>
              <el-button @click="addClick" style="font-size: 22px;margin-left:10px;">+</el-button>
          </el-form-item>
          <el-form-item label="标签类型" prop="tagType">
            <el-radio-group v-model="editData.tagType">
              <el-radio :value="item.value" v-for="item,index in tagDataArr" :key="index">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="tagState">
              <FISelect
                  v-model="editData.tagState"
                  valueCustom="value"
                  :options="dataArr"
                  clearable
                />
          </el-form-item>
          <el-form-item label="描述" prop="remark">
            <FIInput v-model="editData.remark" clearable type="textarea"/>
          </el-form-item>
          
        </el-form>
        <template #footer>
            <slot name="footer">
              <div class="dialog-footer">
                <el-button border @click="closeClick">取消</el-button>
                <FIButton id="saveTag" border @click="saveFunc(ruleFormRef)"> 确定 </FIButton>
              </div>
            </slot>
          </template>
    </FIModel>
    <el-drawer v-model="drawer" :direction="direction" :modal="true" :append-to-body="true" modal-class="mask-layer">
        <template #header>
          <h4>标签分组</h4>
        </template>
        <template #default>
          <FIFormItem prop="groupCode" label="标签分组编码">
            <FIInput v-model="groupCode" clearable />
          </FIFormItem>
          <FIFormItem prop="groupName" label="分组名称">
            <FIInput v-model="groupName" clearable />
          </FIFormItem>
          <FIFormItem prop="sortId" label="排序">
            <FIInput v-model="sortId" clearable type="number"/>
          </FIFormItem>
        </template>
        <template #footer>
          <div style="flex: auto">
            <el-button @click="cancelClick" style="margin-right: 10px">取消</el-button>
            <el-button @click="confirmClick">确定</el-button>
          </div>
        </template>
      </el-drawer>
    </div>
  </template>
  <script lang="ts" setup>
  import { reactive, onMounted, ref, computed, watch,defineEmits } from 'vue'
  import FISearchForm from '@/components/FISearchForm.vue'
  import FIFormItem from '@/components/FIFormItem.vue'
  import FIInput from '@/components/FIInput.vue'
  import FIButton from '@/components/FIButton.vue'
  import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
  import FITable from '@/components/FITable/index.vue'
  import type { DrawerProps } from 'element-plus'
  import tagGroupSelect from '../../plus/tagGroupSelect.vue'
  import { useMessage, useMessageBox } from '@/hooks/message'
  import type { PageConfig, Column } from '@/types/components'
  import { useRoute } from 'vue-router'
  import { initSearchData } from '@/utils/common'
  import { getQueryTableCache } from '@/utils/cacheUtils'
  import {
    apiQueryTag,apiEnableTag,apiDisableTag,apiDeleteTag,apiQueryDtTaggroup,apiSaveTag,apiSaveDtTaggroup
    
  } from '@/api/modules/GM.js'
  import {
  apiGetCodeitems,
} from '@/api/configEnvMaint/index.ts'
  const route = useRoute()
  const searchWrapperSpan = 8
  const isTableLoading = ref(false)
  const isEdit = ref(false)
  // 页面编码
  const tableId = 'assigneecfg'
  // 保存成功按钮状态，默认不展示底部保存，取消按钮
  const saveSuccessful = ref(false)
  const editData = ref({
    tagCode:'',
    tagName:'',
    tagType:'',
    groupCode:'',
    tagState:'',
    remark:'',
  })
  const tableRef = ref(null)
  const groupName = ref('')
  const groupCode = ref('')
  const nodeSearchArr = ref([])
  const drawer = ref(false)
  const direction = ref<DrawerProps['direction']>('rtl')
  const editShow = ref(false)
 
  const registerRules = reactive({
    loginName: [{ required: true, message: '此为必填项', trigger: 'blur' }],
    userName:[{ required: true, message: '此为必填项', trigger: 'blur' }],
    // mobile:[{ required: true,validator: validatePhone, trigger: 'blur' }],
    email:[
      {required: true,message: '此为必填项',trigger: 'blur',},
      {type: 'email',message: '请输入正确的email地址',trigger: ['blur', 'change'],}
    ]
  })
  const props = defineProps({
    data: {
        type: Array,
        default: () => [],
    },
    activeName:{
      type: String,
      default:'1',
    }
  })
  const state = reactive({
    query: {
        tagCode: '',
        tagName: '',
        groupCode: '',
        tagState: '1',
        current: 1,
        size: 10,
    },
    dataList: [],
  })
  const pageConfig: PageConfig = reactive({
    total: 0,
    currentPage: 1,
  })
  const dataArr = ref([])
  const tagDataArr = ref([])
  const columns: Column[] = reactive([
    {
      label: '标签编码',
      prop: 'tagCode',
      align: 'center',
      editable: false,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '标签名称',
      prop: 'tagName',
      align: 'center',
      editable: false,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
        label: '标签类型',
        prop: 'tagType',
        align: 'center',
        editable: false,
        editType: 'select',
        modelValue: [],
        editConfig: {
          options: tagDataArr,
          selectBinds: {
                multiple: false,
                valueCustom: 'value',
            },
        },
    },
    {
        label: '标签状态',
        prop: 'tagState',
        align: 'center',
        editable: false,
        editType: 'select',
        // editConfig: {
        //   rules: { type: [{ required: true, message: '请选择类型', trigger: 'change' }] },
        //   options: dataArr,
        // },
        modelValue: [],
        // options: dataArr,
        editConfig: {
            options: dataArr,
            selectBinds: {
                multiple: false,
                valueCustom: 'value',
            },
        },
    },
    {
      label: '标签分组',
      prop: 'groupName',
      align: 'center',
      editable: false,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '描述',
      prop: 'remark',
      editable: true,
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '创建人',
      prop: 'recCreator',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '创建时间',
      prop: 'recCreateTime',
      align: 'center',
      editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '最后修改人',
      prop: 'recRevisor',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '最后修改时间',
      prop: 'recReviseTime',
      align: 'center',
      editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '',
      prop: 'action',
      actionConfig: [
        { id: 'editTag', type: 'edit' },
        { id: 'deleteTag', type: 'delete' },
        { id: 'enableTag', type: 'open' },
        { id: 'disableTag', type: 'stop' },
      ],
    },
  ])
  
  const checkedRows = ref([])
  const sortId = ref('')
  const handleSelectionChange = (e) => {
    checkedRows.value = e
  }
  const handleSizeChange = (e) => {
    pageConfig.pageSize = e
    pageConfig.currentPage = 1
    searchFn()
  }
  const btnClick = () => {
    isEdit.value = false
    editData.value.tagCode = ''
    editData.value.tagName = ''
    editData.value.tagType = ''
    editData.value.groupCode = ''
    editData.value.tagState = ''
    editData.value.remark = ''
    editShow.value = true
  }
  const addClick = () => {
    drawer.value = true
  }
  const confirmClick = () =>{
    let par = {
      _isNew: 1,
      groupName:groupName.value,
      groupCode:groupCode.value,
      sortId:sortId.value

    }
    apiSaveDtTaggroup([par])
    .then((res) => {
      console.log(res, '小代码')
      if (res.data.success) {
        drawer.value = false
      }
    })
    .catch((error: any) => {})
  }
  const cancelClick = () => {
    drawer.value = false
  }
  const tagSmallCode = () =>{
    apiGetCodeitems({ codesetCode: 'gm.dt.tagType' })
    .then((res) => {
      console.log(res, '小代码')
      if (res.data.success) {
        tagDataArr.value = res.data.data.map((v) => {
          return {
            label: v.itemCname,
            value: v.itemCode,
          }
        })
        tableRef.value.cloneColumnList.forEach((v) => {
          if (v.prop == 'tagType') {
            v.editConfig.options = tagDataArr
          }
        })
      }
    })
    .catch((error: any) => {})
  }
  const smallCode = () => {
  apiGetCodeitems({ codesetCode: 'gm.dt.tagState' })
    .then((res) => {
      if (res.data.success) {
        dataArr.value = res.data.data.map((v) => {
          return {
            label: v.itemCname,
            value: v.itemCode,
          }
        })
        tableRef.value.cloneColumnList.forEach((v) => {
          if (v.prop == 'tagState') {
            v.editConfig.options = dataArr
          }
        })
      }
    })
    .catch((error: any) => {})
}
  //操作
  const actionClick = (item, rowData, btnInfo) => {
    console.log(item,rowData,btnInfo, 'rowData')
    if(item.type == 'open'){
      openApi(rowData.tagId)
    }else if(item.type == 'stop'){
      stopApi(rowData.tagId)
    }else if(item.type == 'edit'){
      editData.value = JSON.parse(JSON.stringify(rowData))
      isEdit.value = true
      console.log(editData,'ppppp')
      editShow.value = true
    }else if(item.type == 'delete'){
      useMessageBox().confirm(`您确认要删除吗？`, '提示').then(() => {
        deleteApi(rowData.tagId)
      })
      .catch(() => {})
    }
  }
  const deleteApi = (tagId) =>{
    
    apiDeleteTag({ tagId })
      .then((res) => {
        
        if (res.data.success) {
          useMessage().success(res.data.message)
          searchFn()
        }
      })
      .catch((error: any) => {
        useMessage().error(error.data.message)
      })
  }
  const stopApi = (tagId) =>{
    apiDisableTag({ tagId })
      .then((res) => {
        
        if (res.data.success) {
          useMessage().success(res.data.message)
          searchFn()
        }
      })
      .catch((error: any) => {
        useMessage().error(error.data.message)
      })
  }
  const openApi = (tagId) =>{
    apiEnableTag({ tagId })
      .then((res) => {
        
        if (res.data.success) {
          useMessage().success(res.data.message)
          searchFn()
        }
      })
      .catch((error: any) => {
        useMessage().error(error.data.message)
      })
    
  } 
  const handleCurrentChange = (e) => {
    pageConfig.currentPage = e
    searchFn()
  }
  const searchFn = (type?: string, columnsVal?: any) => {
    const obj = initSearchData(type, columnsVal, columns, state.query)
    state.query = obj.queryData
    columns.values = obj.columns
  
    state.query.current = pageConfig.currentPage
    isTableLoading.value = true
    if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
    apiQueryTag(state.query)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          state.dataList = res.data.data.result
          pageConfig.pageSize = Number(res.data.data.size)
          pageConfig.total = Number(res.data.data.count)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  const closeClick = () =>{
    editShow.value = false
  }
  const saveFunc = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        let par = {
          _isNew: 1,
          ...editData.value
        }
        apiSaveTag(par)
        .then((res) => {
          if(res.data.success){
            editShow.value = false
            searchFn()
            useMessage().success(res.data.message)
            
          }
        })
        .catch((error: any) => {
          
        })
      }
    })
  }
  const ruleFormRef = ref(null)
  // watch(() => props.activeName,(val) => {
  //   console.log(val,'左边')
  //     searchFn()
  //   },
  //   { deep: true }
  // )
  onMounted(() => {
    smallCode()
    tagSmallCode()
    // 获取查询条件缓存
    const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
    if (cachedQuery) state.query = cachedQuery
    if (columns) columns.values = cachedColumns
    searchFn()
  })
  </script>
  <style lang="less" scoped></style>
  